package com.naszetatry.profiles;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.naszetatry.beans.User;
import com.naszetatry.controller.RegistrationController;
import com.naszetatry.controller.UserController;
import com.naszetatry.exception.InvalidLoginException;
import com.naszetatry.exception.InvalidMailException;
import com.naszetatry.exception.InvalidPasswordException;
import com.naszetatry.logic.UserLogic;
import com.naszetatry.registration.RValidation;
/**
 * Serwlet odpowiedzialny za ustawienia uzytkownika.
 * @author Maciej Koch
 *
 */
public class Settings extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		if("1".equals(request.getParameter("do"))) {
			getServletContext().getRequestDispatcher("/jsp/settings.jsp").forward(request, response);
			return;
		}
		
		String oldPass = request.getParameter("old_password");
		String newPass1 = request.getParameter("new_password1");
		String newPass2 = request.getParameter("new_password2");
		
		RValidation validation = new RValidation();
		validation.isPasswordMatch = validation.isPasswordMatch(newPass1, newPass2);
		boolean settingsAccepted = true;
		
		if(validation.isPasswordMatch) {
			User oldUser = new User();
			oldUser.setLogin(UserController.getUser(request.getSession()).getLogin());
			oldUser.setPassword(oldPass);
			User newUser = new User();
			newUser.setPassword(newPass1);
			
			try {
				UserLogic.update(oldUser, newUser);
			} catch (InvalidPasswordException e) {
				validation.isPasswordValid = false;
			} catch (InvalidMailException e) {
				//irrelevant
			} catch (InvalidLoginException e) {
				//irrelevant
			}		
		}
		if(validation.isPasswordMatch && validation.isPasswordValid)
			validation.isPasswordChangedCorrectly = true;
		
		RegistrationController.setValidation(request, validation);
		getServletContext().getRequestDispatcher("/jsp/settings.jsp").forward(request, response);
		
	}
}
